import { EntityManager, MikroORM } from '@mikro-orm/mysql';
import { InjectEntityManager, InjectMikroORM } from '@mikro-orm/nestjs';
import { Body, Controller, Get, Inject, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { JsonApiResponse } from '@utils/json.api.response';
import { QiniuService } from '../service/qiniu.service';
import { knext } from 'knext';
import { ImsYzdKpStorage } from '@databases/entities/ims_yzd_kp/ImsYzdKpStorage';
import { ImsYzdKpStorageList } from '@entities/ims_yzd_kp/ImsYzdKpStorageList';
import dayjs from 'dayjs';
import imageSize from 'image-size';
import * as Path from 'path';
import { existsSync, mkdirSync, stat, statSync } from 'fs';
import { statfs } from 'fs/promises';
import { ConfigService } from '@nestjs/config';
import { OrderJobEnrolls } from '@databases/entities/OrderJobEnrolls';
import { Users } from '@databases/entities/Users';
import * as XLSX from 'xlsx'

@ApiTags('(站点) 存储')
@Controller('storage')
export class StorageController {
    constructor(
        @InjectMikroORM('zp')
        private readonly orm : MikroORM,
        @InjectEntityManager('zp')
        private readonly em : EntityManager,
        private readonly qiniuService : QiniuService,
        private readonly configService : ConfigService
    ){}

    @ApiOperation({summary:'文件上传'})
    @Post('upload')
    @UseInterceptors(FileInterceptor('avatar'))
    upload(@UploadedFile() file : Express.Multer.File) {
        file.path = file.path.replace(/\\/g, '/');
        return JsonApiResponse.object({path:file.path})
    }

    @ApiOperation({summary:'文件上传(图片)'})
    @Post('upload/image')
    @UseInterceptors(FileInterceptor('image'))
    async uploadImage(@UploadedFile() file : Express.Multer.File) {
        file.path = file.path.replace(/\\/g, '/');
        //const url  =await this.qiniuService.uploadFile(file);
        return JsonApiResponse.object({path:file.path})
    }

    @ApiOperation({summary:'媒体文件上传'})
    @Post('upload/media')
    @UseInterceptors(FileInterceptor('media'))
    uploadMedia(@UploadedFile() file : Express.Multer.File) {
        //file.path = file.path.replace(/\\/g, '/');
        let url = `${this.configService.get('storage_url')}/${file.path}`
        let info = imageSize(file.path)
        return JsonApiResponse.object({
            url,
            path:file.path,
            size:file.size,
            name:file.filename,
            width:info.width,
            height:info.height,
            type:info.type
        })
    }

    @Post('xlsx')
    async xlsx(
        @Body('task_id') task_id
    ){
        let knex = knext(this)

        let result = await knex.fromORM(OrderJobEnrolls)
        .selectAll()
        .where({job_task_id:task_id})
        .withEntity(Users,'enroller')
        .populate()

        result = result.map(r=>{
            return {
                name:r.enroller.name, //兼职姓名
                phone_number:r.enroller.phone_number,//兼职电话
                id_number:r.enroller.id_number, //兼职身份证
                bank_number:r.enroller.bank_number,//银行卡号
                bank_account: r.enroller.bank_account,//开户行
                bank_address: r.enroller.bank_address, //开户地址
                sign_up_at: r.sign_up_at, //签到时间
                sign_down_at: r.sign_down_at, //签离时间
                verified_at: r.verified_at, //验收时间
                verifier: 'JASON', //验收人
                give_salary_at:r.verified_at,//发薪时间
                salary: r.salary, //发薪数量
            }
        })

        result = result.map(r=>[
            r.name,
            r.phone_number,
            r.id_number,
            r.bank_number,
            r.bank_account,
            r.bank_address,
            r.sign_up_at,
            r.sign_down_at,
            r.verified_at,
            r.verifier,
            r.give_salary_at,
            r.salary,
        ])

        result.unshift([
            '兼职姓名',
            '兼职电话',
            '兼职身份证',
            '银行卡号',
            '开户行',
            '开户地址',
            '签到时间',
            '签离时间',
            '验收时间',
            '验收人',
            '发薪时间',
            '发薪数量',
        ])

        const worksheet = XLSX.utils.aoa_to_sheet(result)

        // 创建工作簿对象
        const workbook = { Sheets: {}, SheetNames: [] };
        workbook.Sheets['Sheet1'] = worksheet;
        workbook.SheetNames.push('Sheet1');

        // 生成 Excel 文件
        //XLSX.writeFile(workbook, 'output.xlsx');
        //var data = XLSX.write(workbook,{}) as Uint8Array
        
        let cwd = process.cwd()
        let out = Path.join(`/public/${dayjs().format('YYYY-MM-DD')}`)
        let name = `${dayjs().valueOf()}.xlsx`

        if(!existsSync(Path.join(cwd,out)))
        {
            mkdirSync(Path.join(cwd,out))
        }

        let savepath = Path.join(cwd,out,name)
        XLSX.writeFile(workbook,savepath)
        console.log("Excel 文件已生成！");

        return JsonApiResponse.object(Path.join(out,name))

        //XLSX.utils.aoa_to_sheet()
    }
}
